<?php

namespace app\controller;

use support\Request;
use support\Response;

class AdController
{
    /**
     * 获取广告列表
     */
    public function list(Request $request): Response
    {
        $position = $request->get('position', 'home');
        $status = $request->get('status', 'active');

        // 模拟广告数据
        $ads = [
            [
                'id' => 1,
                'title' => '无尽冬日',
                'desc' => '大哥,来一局?',
                'image' => '/images/ad1.jpg',
                'url' => 'https://example.com/game1',
                'position' => 'home',
                'status' => 'active',
                'sort' => 1,
                'created_at' => '2025-10-16 23:00:00'
            ],
            [
                'id' => 2,
                'title' => '欢乐斗地主',
                'desc' => '经典玩法，等你来战',
                'image' => '/images/ad2.jpg',
                'url' => 'https://example.com/game2',
                'position' => 'home',
                'status' => 'active',
                'sort' => 2,
                'created_at' => '2025-10-16 23:00:00'
            ],
            [
                'id' => 3,
                'title' => '精彩游戏推荐',
                'desc' => '发现更多有趣游戏',
                'image' => '/images/ad1.jpg',
                'url' => 'https://example.com/game3',
                'position' => 'profile',
                'status' => 'active',
                'sort' => 1,
                'created_at' => '2025-10-16 23:00:00'
            ],
            [
                'id' => 4,
                'title' => '游戏攻略',
                'desc' => '成为高手的秘密',
                'image' => '/images/ad2.jpg',
                'url' => 'https://example.com/strategy',
                'position' => 'profile',
                'status' => 'active',
                'sort' => 2,
                'created_at' => '2025-10-16 23:00:00'
            ]
        ];

        // 根据位置和状态过滤
        $filteredAds = array_filter($ads, function($ad) use ($position, $status) {
            return $ad['position'] === $position && $ad['status'] === $status;
        });

        // 按排序字段排序
        usort($filteredAds, function($a, $b) {
            return $a['sort'] - $b['sort'];
        });

        return json([
            'success' => true,
            'data' => [
                'ads' => array_values($filteredAds)
            ]
        ]);
    }

    /**
     * 记录广告点击
     */
    public function click(Request $request): Response
    {
        $data = $request->post();
        $adId = $data['ad_id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        $position = $data['position'] ?? 'home';

        if (!$adId) {
            return json(['success' => false, 'message' => '广告ID不能为空']);
        }

        // 这里可以记录到数据库
        // 暂时只返回成功
        return json([
            'success' => true,
            'message' => '广告点击记录成功'
        ]);
    }
}